<template>
  <div class="enhanced-host-management">
    <!-- 状态概览 -->
    <div class="status-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon online">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ summary.online_hosts }}</div>
                <div class="status-label">在线主机</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon offline">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ summary.offline_hosts }}</div>
                <div class="status-label">离线主机</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon warning">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ summary.warning_hosts }}</div>
                <div class="status-label">告警主机</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon total">
                <el-icon><Box /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ summary.total_hosts }}</div>
                <div class="status-label">总主机数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>主机管理</span>
          <div class="header-actions">
            <el-button @click="showMonitoringDashboard">
              <el-icon><TrendCharts /></el-icon>
              监控仪表盘
            </el-button>
            <el-button @click="showSSHTerminal">
              <el-icon><Monitor /></el-icon>
              SSH终端
            </el-button>
            <el-button type="success" @click="showImport">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button @click="showExport">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加主机
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索主机名、IP地址"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.environment" placeholder="选择环境" clearable>
              <el-option 
                v-for="env in environments" 
                :key="env.id" 
                :label="env.name" 
                :value="env.id" 
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="在线" value="online" />
              <el-option label="离线" value="offline" />
              <el-option label="维护中" value="maintenance" />
              <el-option label="故障" value="error" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
          <el-col :span="6">
            <div class="batch-actions">
              <el-button 
                :disabled="selectedHosts.length === 0"
                @click="batchEnable"
              >
                批量启用
              </el-button>
              <el-button 
                :disabled="selectedHosts.length === 0"
                @click="batchDisable"
              >
                批量禁用
              </el-button>
              <el-button 
                type="danger"
                :disabled="selectedHosts.length === 0"
                @click="batchDelete"
              >
                批量删除
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 主机列表 -->
      <el-table 
        :data="hostList" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="margin-top: 20px;"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hostname" label="主机名" width="150" />
        <el-table-column prop="ip" label="IP地址" width="120" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              <el-icon><component :is="getStatusIcon(row.status)" /></el-icon>
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="CPU使用率" width="120">
          <template #default="{ row }">
            <div v-if="row.metrics">
              <el-progress 
                :percentage="row.metrics.cpu_usage" 
                :color="getProgressColor(row.metrics.cpu_usage)"
                :show-text="false"
                style="width: 80px;"
              />
              <span class="metric-text">{{ row.metrics.cpu_usage.toFixed(1) }}%</span>
            </div>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column label="内存使用率" width="120">
          <template #default="{ row }">
            <div v-if="row.metrics">
              <el-progress 
                :percentage="row.metrics.memory_usage" 
                :color="getProgressColor(row.metrics.memory_usage)"
                :show-text="false"
                style="width: 80px;"
              />
              <span class="metric-text">{{ row.metrics.memory_usage.toFixed(1) }}%</span>
            </div>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column label="磁盘使用率" width="120">
          <template #default="{ row }">
            <div v-if="row.metrics">
              <el-progress 
                :percentage="row.metrics.disk_usage" 
                :color="getProgressColor(row.metrics.disk_usage)"
                :show-text="false"
                style="width: 80px;"
              />
              <span class="metric-text">{{ row.metrics.disk_usage.toFixed(1) }}%</span>
            </div>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="environment_name" label="环境" width="100" />
        <el-table-column prop="host_type_name" label="类型" width="100" />
        <el-table-column label="最后心跳" width="160">
          <template #default="{ row }">
            <span v-if="row.last_heartbeat">
              {{ formatTime(row.last_heartbeat) }}
            </span>
            <span v-else class="no-data">从未连接</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button-group size="small">
              <el-button type="primary" @click="viewHostDetail(row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button 
                type="success" 
                @click="connectSSH(row)"
                :disabled="row.status !== 'online'"
              >
                <el-icon><Monitor /></el-icon>
                SSH
              </el-button>
              <el-button @click="testConnection(row)">
                <el-icon><Connection /></el-icon>
                测试
              </el-button>
              <el-button @click="editHost(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button 
                type="danger" 
                @click="deleteHost(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 监控仪表盘对话框 -->
    <el-dialog
      v-model="showMonitoringDialog"
      title="监控仪表盘"
      width="90%"
      :close-on-click-modal="false"
    >
      <MonitoringDashboard />
    </el-dialog>

    <!-- SSH终端对话框 -->
    <el-dialog
      v-model="showSSHDialog"
      title="SSH终端"
      width="90%"
      :close-on-click-modal="false"
      custom-class="ssh-dialog"
    >
      <SSHTerminal :host-id="selectedHostId" />
    </el-dialog>

    <!-- 主机详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="主机详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <HostDetail v-if="selectedHost" :host="selectedHost" />
    </el-dialog>

    <!-- 导入导出组件 -->
    <HostImportExport
      ref="importExportRef"
      :selected-hosts="selectedHosts"
      :filter-params="getFilterParams()"
      @import-success="handleImportSuccess"
      @export-success="handleExportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Monitor, Warning, WarningFilled, Box, TrendCharts, Plus, Upload,
  Search, View, Edit, Delete, Connection, CircleCheckFilled, 
  CircleCloseFilled, Clock
} from '@element-plus/icons-vue'
import MonitoringDashboard from '@/components/monitoring/MonitoringDashboard.vue'
import SSHTerminal from '@/components/ssh/SSHTerminal.vue'
import HostDetail from './HostDetail.vue'
import HostImportExport from '@/components/cmdb/HostImportExport.vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const hostList = ref([])
const selectedHosts = ref([])
const selectedHost = ref(null)
const selectedHostId = ref(null)
const environments = ref([])
const importExportRef = ref()

// 对话框状态
const showMonitoringDialog = ref(false)
const showSSHDialog = ref(false)
const showDetailDialog = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  environment: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 状态摘要
const summary = reactive({
  total_hosts: 0,
  online_hosts: 0,
  offline_hosts: 0,
  warning_hosts: 0,
  critical_hosts: 0
})

// 自动刷新
let refreshInterval: number | null = null

// 获取主机列表
const fetchHostList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      page_size: pagination.size,
      search: searchForm.keyword,
      environment: searchForm.environment,
      status: searchForm.status
    }
    
    const response = await api.get('/cmdb/hosts/', { params })
    if (response.data.success) {
      hostList.value = response.data.data.results
      pagination.total = response.data.data.count
      
      // 获取实时监控数据
      await fetchRealtimeMetrics()
    }
  } catch (error) {
    console.error('获取主机列表失败:', error)
    ElMessage.error('获取主机列表失败')
  } finally {
    loading.value = false
  }
}

// 获取实时监控数据
const fetchRealtimeMetrics = async () => {
  try {
    const response = await api.get('/monitoring/metrics/realtime/')
    if (response.data.success) {
      const metricsMap = new Map()
      response.data.data.forEach(metric => {
        metricsMap.set(metric.host, metric)
      })
      
      // 将监控数据关联到主机列表
      hostList.value.forEach(host => {
        host.metrics = metricsMap.get(host.id)
      })
    }
  } catch (error) {
    console.error('获取监控数据失败:', error)
  }
}

// 获取状态摘要
const fetchSummary = async () => {
  try {
    const response = await api.get('/cmdb/hosts/summary/')
    if (response.data.success) {
      Object.assign(summary, response.data.data)
    }
  } catch (error) {
    console.error('获取状态摘要失败:', error)
  }
}

// 获取环境列表
const fetchEnvironments = async () => {
  try {
    const response = await api.get('/cmdb/environments/active/')
    if (response.data.success) {
      environments.value = response.data.data
    }
  } catch (error) {
    console.error('获取环境列表失败:', error)
  }
}

// 工具函数
const getStatusType = (status: string) => {
  const typeMap = {
    'online': 'success',
    'offline': 'danger',
    'maintenance': 'warning',
    'error': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusIcon = (status: string) => {
  const iconMap = {
    'online': 'CircleCheckFilled',
    'offline': 'CircleCloseFilled',
    'maintenance': 'Clock',
    'error': 'WarningFilled'
  }
  return iconMap[status] || 'Monitor'
}

const getStatusText = (status: string) => {
  const textMap = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护',
    'error': '故障'
  }
  return textMap[status] || '未知'
}

const getProgressColor = (value: number) => {
  if (value >= 90) return '#F56C6C'
  if (value >= 70) return '#E6A23C'
  return '#67C23A'
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

// 事件处理
const handleSearch = () => {
  pagination.page = 1
  fetchHostList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    environment: '',
    status: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection: any[]) => {
  selectedHosts.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchHostList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchHostList()
}

// 操作函数
const showMonitoringDashboard = () => {
  showMonitoringDialog.value = true
}

const showSSHTerminal = () => {
  showSSHDialog.value = true
}

const viewHostDetail = (host: any) => {
  selectedHost.value = host
  showDetailDialog.value = true
}

const connectSSH = (host: any) => {
  selectedHostId.value = host.id
  showSSHDialog.value = true
}

const testConnection = async (host: any) => {
  try {
    ElMessage.info('正在测试连接...')
    const response = await api.post(`/cmdb/hosts/${host.id}/test_connection/`)
    if (response.data.success) {
      ElMessage.success('连接测试已启动')
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败')
  }
}

const editHost = (host: any) => {
  // 编辑主机逻辑
  ElMessage.info('编辑功能开发中')
}

const deleteHost = async (host: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除主机 "${host.hostname}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await api.delete(`/cmdb/hosts/${host.id}/`)
    if (response.data.success) {
      ElMessage.success('主机删除成功')
      fetchHostList()
      fetchSummary()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除主机失败:', error)
      ElMessage.error('删除主机失败')
    }
  }
}

const showAddDialog = () => {
  ElMessage.info('添加主机功能开发中')
}

const showImport = () => {
  importExportRef.value?.showImport()
}

const showExport = () => {
  importExportRef.value?.showExport()
}

const getFilterParams = () => {
  return {
    search: searchForm.keyword,
    environment: searchForm.environment,
    status: searchForm.status
  }
}

const handleImportSuccess = () => {
  ElMessage.success('主机导入成功')
  fetchHostList()
  fetchSummary()
}

const handleExportSuccess = () => {
  ElMessage.success('主机导出成功')
}

// 批量操作
const batchEnable = async () => {
  try {
    const hostIds = selectedHosts.value.map(host => host.id)
    const response = await api.post('/cmdb/hosts/batch_operation/', {
      host_ids: hostIds,
      operation: 'enable'
    })
    
    if (response.data.success) {
      ElMessage.success(response.data.data.message)
      fetchHostList()
      fetchSummary()
    }
  } catch (error) {
    console.error('批量启用失败:', error)
    ElMessage.error('批量启用失败')
  }
}

const batchDisable = async () => {
  try {
    const hostIds = selectedHosts.value.map(host => host.id)
    const response = await api.post('/cmdb/hosts/batch_operation/', {
      host_ids: hostIds,
      operation: 'disable'
    })
    
    if (response.data.success) {
      ElMessage.success(response.data.data.message)
      fetchHostList()
      fetchSummary()
    }
  } catch (error) {
    console.error('批量禁用失败:', error)
    ElMessage.error('批量禁用失败')
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHosts.value.length} 台主机吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const hostIds = selectedHosts.value.map(host => host.id)
    const response = await api.post('/cmdb/hosts/batch_operation/', {
      host_ids: hostIds,
      operation: 'delete'
    })
    
    if (response.data.success) {
      ElMessage.success(response.data.data.message)
      fetchHostList()
      fetchSummary()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 自动刷新
const startAutoRefresh = () => {
  refreshInterval = setInterval(() => {
    fetchRealtimeMetrics()
    fetchSummary()
  }, 30000) // 30秒刷新一次
}

const stopAutoRefresh = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
}

// 生命周期
onMounted(() => {
  fetchHostList()
  fetchSummary()
  fetchEnvironments()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.enhanced-host-management {
  padding: 20px;
}

.status-overview {
  margin-bottom: 20px;
}

.status-card {
  border-radius: 8px;
  overflow: hidden;
}

.status-content {
  display: flex;
  align-items: center;
  padding: 15px;
}

.status-icon {
  font-size: 32px;
  margin-right: 15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-icon.online {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.status-icon.offline {
  background: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.status-icon.warning {
  background: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.status-icon.total {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.status-info .status-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.status-info .status-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.metric-text {
  margin-left: 8px;
  font-size: 12px;
  color: #606266;
}

.no-data {
  color: #C0C4CC;
  font-style: italic;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.ssh-dialog) {
  .el-dialog__body {
    padding: 0;
    height: 70vh;
  }
}
</style>
